package com.thomasbrault.display 
{	import flash.display.BitmapData;	
	import flash.geom.Matrix;	
	import flash.display.Bitmap;		import flash.events.Event;	
	import flash.net.URLRequest;	
	import flash.system.LoaderContext;	
	import flash.display.Loader;
	
	/**	 * @author thomasbrault	 */	public class AdvandcedLoader extends Loader 
	{
		
		private var _smoothing : Boolean = true;
		
		private var _targetWidth : Number;
		private var _targetHeight : Number;
		private var _method : String;
		
		public var bitmap : Bitmap;
		
		public function advancedLoad ( req : URLRequest, width : Number, height : Number, method : String = 'crop', convertBitmapAndSmooth : Boolean = true ) : void
		{
			
			_targetWidth = width;
			_targetHeight = height;
			_method = method;
			_smoothing = convertBitmapAndSmooth;
			
			contentLoaderInfo.addEventListener(Event.COMPLETE, _onComplete,false,1);
			
			load(req,null);
			
		}
		
		private function _onComplete(event : Event) : void
		{

			contentLoaderInfo.removeEventListener(Event.COMPLETE,_onComplete);

			var scale : Number;

			switch ( _method )
			{
				case 'crop':
					scale = Math.max (  _targetWidth/content.width, _targetHeight/content.height );
				break;
				case 'fit':
					scale = Math.min ( _targetWidth/content.width, _targetHeight/content.height );
				break;
				default:
					throw new Error('AdvancedLoader error : this method does not exist');
				break;
			}
			
			
			if ( _smoothing )
			{
				var matrix : Matrix = new Matrix;
				matrix.scale(scale, scale);	
				
				var bmd : BitmapData = new BitmapData(content.width, content.height, true, 0x00000000);
				bmd.draw(content,null,null,null,null,true);

				bitmap = new Bitmap(bmd,"auto",true);
				bitmap.smoothing = true;
				bitmap.scaleX = bitmap.scaleY = scale;
			} else {
				content.scaleX = content.scaleY = scale;
			}
		}

	}}